<template>
  <div class="ShoppingTrunk">
    <!-- 有设置收货地址 -->
    <div v-if="cartGoodslist.length > 0" class="addressWrap">
      <div v-if="hasAddress" class="address">
        <van-icon name="location-o" />
        <div class="info" @click="$router.push('/address')">
          <div>
            {{ address.name }} / {{ address.tel }} 邮编:
            {{ address.postalCode }}
          </div>
          <div>
            {{ address.province }}{{ address.city }}{{ address.country
            }}{{ address.addressDetail }}
          </div>
        </div>
      </div>
      <!-- 无设置收货地址 -->
      <div
        v-else
        class="address"
        style="text-align: center"
        @click="$router.push('/address')"
      >
        添加地址
      </div>
    </div>
    <div class="ShoppingCartList">
      <div class="item" v-for="(item, index) in cartGoodslist" :key="item.id">
        <van-checkbox
          @click="
            ChangeBox(item.id, $store.getters.getGoodsStatusById[item.id])
          "
          v-model="$store.getters.getGoodsStatusById[item.id]"
          icon-size="24px"
          checked-color="skyblue"
        />
        <div class="imgWrap">
          <img :src="item.thumb_path" />
        </div>
        <div class="iteminfo">
          <div class="title">{{ item.title }}</div>
          <div class="area">
            <div class="price">&yen;{{ item.sell_price }}</div>
            <van-stepper
              @change="NumChange($event, item.id)"
              v-model="$store.getters.getGoodsNumberById[item.id]"
              theme="round"
              button-size="22"
              disable-input
            />
            <van-button
              type="danger"
              @click="DeleteSelectedItems(item.id, index)"
              >删除</van-button
            >
          </div>
        </div>
      </div>
    </div>
    <!-- 没有购物车商品时展示 -->
    <div class="emptyCar" v-if="cartGoodslist.length === 0">
      <van-empty
        class="custom-image"
        :image="emptyCar"
        description="你的购物车空空如也"
      >
        <van-button
          @click="$router.replace('/home')"
          type="danger"
          class="bottom-button"
          >去首页</van-button
        >
      </van-empty>
    </div>
    <!-- 订单支付 -->
    <van-submit-bar
      :class="{ mb50: isMainPage }"
      :price="$store.getters.allPrice * 100"
      button-text="提交订单"
      :disabled="cartGoodslist.length === 0"
      button-color="#7232dd"
      @submit="onSubmit"
    >
      <template #tip> 仅支持微信支付，请在微信客户端中打开 </template>
      <template #default>
        共选中 {{ $store.getters.ItemSelectedNum }} 件
      </template>
    </van-submit-bar>
  </div>
</template>

<script>
import { fetchCartGoods } from "@/api/index";
import { fetchGetUserAddress } from "@/api/address";
import { genOrderId } from "@/util/tools.js";
import { fetchCommitOrder } from "@/api/order.js";
export default {
  data() {
    return {
      cartGoodslist: [],
      ids: this.$store.getters.getGoodsIds, //拿取到id
      address: {},
      hasAddress: false,
      emptyCar: require("@/img/images/logo2.png"),
      isMainPage: false,
    };
  },
  created() {
    if (this.$parent.fromRoute) {
      this.isMainPage = !!this.$parent.fromRoute.meta.mainPage;
    } else {
      // 刷新页面会走这里
      // 防止页面刷新此值this.$parent.fromRoute为空
      this.isMainPage = true;
    }

    this._fetchCartGoods();
    // 判断本地存储是否有默认地址，有则直接使用，没有在发起地址的请求
    this.address = JSON.parse(localStorage.getItem("harvestAddress") || "{}");
    // 记录是否有默认的收货地址
    let isHarvestAddress =
      Object.keys(this.address).length === 0 ? false : true;
    this.hasAddress = isHarvestAddress;

    if (!this.hasAddress) {
      this._fetchUserAddress();
    }
  },
  methods: {
    async _fetchCartGoods() {
      let { message } = await fetchCartGoods(this.ids);
      this.cartGoodslist = message;
    },
    async _fetchUserAddress() {
      let user_id = this.$store.state.userInfo.id;
      let userAddressAll = await fetchGetUserAddress(user_id);
      // 判断是否有地址
      this.hasAddress = !!userAddressAll.length;
      // 如果用户只有一个收货地址，则就是默认的收货地址
      if (userAddressAll.length === 1) {
        this.address = userAddressAll[0];
        return;
      }
      // 判断是否默认收货地址
      let defaultIndex = userAddressAll.findIndex(
        (item) => item.isDefault === 1
      );
      if (defaultIndex !== -1) {
        // 找到了默认地址
        this.address = userAddressAll[defaultIndex];
      } else {
        // 若没有默认地址，则取第一个作为默认地址
        this.address = userAddressAll[0];
      }
    },
    async onSubmit() {
      let user_id = this.$store.state.userInfo.id;
      if (!user_id) {
        this.$router.push("/login");
        return;
      }
      // 准备好下订单的数据
      let orderData = {
        user_id,
        order_id: genOrderId(),
        address_id: this.address.id,
        total_price: this.$store.getters.allPrice,
        number: this.$store.getters.ItemSelectedNum,
        goods_ids: this.$store.getters.getGoodsIds,
      };
      // console.log(user_id)
      // console.log(orderData.order_id)
      // console.log(orderData.address_id)
      // console.log(orderData.total_price)
      // console.log(orderData.number)
      // console.log(orderData.goods_ids)
      // 提交订单loading提示
      this.$toast.loading({
        duration: 0, // 持续展示 toast
        message: "提交订单中",
        forbidClick: true,
        overlay: true,
      });
      // 提交订单接口
      let { message, status } = await fetchCommitOrder(orderData);
      this.$toast(message);
      console.log(message);
      // 关闭上面的提示
      if (status == 0) {
        // 下单成功要清购物车，并跳转到订单列表
        this.$store.commit("clearCartData");
        this.$router.replace("/orderlist");
      }

      this.$toast.clear();
    },
    // 删除商品
    DeleteSelectedItems(id, index) {
      // 删除data中的商品
      this.cartGoodslist.splice(index, 1);
      // 删除vuex
      this.$store.commit("DeleteSelectedItems", id);
      console.log(id, index);
    },
    // 切换选中不选中
    ChangeBox(id, selected) {
      console.log(id, selected);
      this.$store.commit("ItemSelectedState", { id, selected });
    },
    NumChange(number, id) {
      this.$store.commit("setGoodsBuyNum", { number, id });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../assets/scss/var.scss";
.ShoppingTrunk {
  height: 100vh;
  background-color: $bgColor;
  padding: 6px;
  ::v-deep .custom-image {
    .van-empty__image {
      img {
        border-radius: 100px;
      }
    }
  }
  .ShoppingCartList {
    .item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 4px;
      background-color: #fff;
      border-radius: 6px;
      margin: 6px 0;

      .imgWrap {
        width: 50px;
        height: 50px;
        padding: 4px;

        img {
          width: 100%;
          height: 100%;
        }
      }

      .iteminfo {
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .title {
          width: 70vw;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
        }

        .area {
          display: flex;
          justify-content: space-between;
          align-items: center;
          .price {
            color: #ff424a;
          }
        }
      }
    }
  }
  .van-submit-bar {
    position: fixed;
    bottom: 50px;
    left: 0;
    z-index: 100;
    width: 100%;
    padding-bottom: constant(safe-area-inset-bottom);
    background-color: #fff;
  }
}
</style>
